package com.iphoon.cn.controller;

import com.google.zxing.common.BitMatrix;
import com.iphoon.cn.util.MyQRUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 二维码打印控制器
 *
 * @author Bob_张
 * @Date 2019/3/14
 */
@Controller
@RequestMapping("/qrPrint")
public class WebPrintController {

    private Logger logger = LoggerFactory.getLogger(MyQRUtils.class);

    @Autowired
    private StringBuffer sb;

    //二维码预览界面
    @GetMapping("/index")
    public String index(Model model) {
        return "ewmPrint";
    }

    @RequestMapping("/printQrFrame")
    public String printQrFrame(Model model, HttpServletRequest request) {
        //String ids = request.getParameter("showId");
        //动态模拟数据
        List listData = new ArrayList();
        String code = "打印00";
        //------------填充数据-------------
        Map<String,Object> map = new HashMap<>();
        map.put("company","百度");
        map.put("address","https://www.baidu.com");
        Map<String,Object> map2 = new HashMap<>();
        map2.put("company","斗鱼直播");
        map2.put("address","https://www.douyu.com/");
        //-------------------------
        listData.add(map2);
        listData.add(map);
        model.addAttribute("showListData", listData);
        return "printFrameQr";
    }

    /**
     * 显示二维码图片
     *
     * @param request
     * @param response
     */
    @RequestMapping("/showImg")
    public void showImgByType(HttpServletRequest request, HttpServletResponse response) {
        String company = request.getParameter("company");
        String address = request.getParameter("address");
        OutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            //图片格式  jpg,jpeg
            String format = "jpg";
            String bottemText = company;//水印文字
            BitMatrix bitMatrix = MyQRUtils.setBitMatrix(address, 180, 180);
            //输出到页面
            MyQRUtils.megerToFile(bitMatrix, format, outputStream, null, bottemText);
        } catch (IOException e) {
            logger.error("二维码生成失败", e);
        } finally {
            try {
                if (outputStream != null) {
                    outputStream.flush();
                    outputStream.close();
                }
            } catch (IOException e) {
                logger.error("关闭数据流出错", e);
            }
        }
    }


}
